import re
import os
from server import base_path

p = base_path
# p = r"D:\Projects\WorkZone\smart-park-server\server"
doc_temp = "# api文档地址: http://127.0.0.1:9191/docs/api/\napp.config['API_DOC_MEMBER'] = [%s]\nApiDoc(app)\n"

with open('controllerTemplate', "r", encoding='utf-8') as file:
    con_temp = file.read()


def un_camelize(input_pattern, separator="_"):
    pattern = re.compile(r'([A-Z]{1})')
    sub = re.sub(pattern, separator + r'\1', input_pattern).lower()[1:]
    return sub


def form(path, file_name, folder, parent, only_desc=False):
    # print(path, file_name, folder, parent)
    with open(path, "r", encoding='utf-8') as f:
        content = f.read()
    class_name = re.search(r"class (.*?)\(BaseOrm", content)
    class_name = class_name[1]
    route_name = un_camelize(class_name)
    route_desc = re.search(r"# (.*?)\nclass", content)
    if not route_desc:
        route_desc = ""
    else:
        route_desc = route_desc[1]
    model_structs = re.findall(r"(.*?) = Column\((.*?), .*? comment=\"(.*?)\"", content)
    model_desc = ""
    if len(model_structs):
        for st in model_structs:
            model_desc += "\n            %s: %s    #%s" % (st[0], st[1], st[2])
    print(class_name, "model_structs", model_structs)
    print(class_name, route_name, route_desc)
    result = con_temp.format(className=class_name, routeName=route_name, routeDesc=route_desc, modelStruct=model_desc)
    controller = file_name
    con_path = os.path.join(parent, controller)
    cont_file = con_path
    if os.path.isfile(cont_file):
        with open(cont_file, "r", encoding='utf-8') as f:
            old_content = f.read()
        after_gen = re.search(r"# >>>>> auto generate end <<<<<\n([\s\S]*)", old_content)

        if after_gen and after_gen[1].strip() != "":
            result += after_gen[1]

    print(result)
    if not only_desc:
        with open(cont_file, "w", encoding="utf-8") as f:
            f.write(result)
    return controller, route_name


def do_trans(ignore_classes=None, ignore_folders=None, expect_classes=None, expect_folders=None, write_route=False, only_desc=False):
    routes = "from server import app\nfrom flask_docs import ApiDoc"
    registers = ""
    model_path = os.path.join(base_path, "model")
    api_path = os.path.join(base_path, "api")
    print(model_path, api_path)
    all_routes = []

    for j in os.listdir(model_path):
        pb = os.path.join(model_path, j)
        print(pb)
        if os.path.isdir(pb):
            continue
        if pb.startswith("__"):
            continue
        if expect_classes and j not in expect_classes:
            continue
        if ignore_classes and j in ignore_classes:
            continue
        cont, route = form(pb, j, model_path, api_path, only_desc)
        # import_str = "from server.model.web.%s import r_%s" % (i, cont, route)
        # reg = "app.register_blueprint(r_%s, url_prefix='/%s')" % (route, route)
        # all_routes.append("\"%s\"" % route)
        # routes += "\n%s" % import_str
        # registers += "\n%s" % reg
    # all_routes = ", ".join(all_routes)
    # all_routes = doc_temp % all_routes
    # import_reg = routes + "\n\n" + registers + "\n\n" + all_routes
    # if write_route:
    #     with open(os.path.join(base_path, "routes.py"), "w", encoding="utf-8") as f:
    #         f.write(import_reg)


if __name__ == '__main__':
    # do_trans(ignore_classes={"role_route.py", "route.py", "sys_user_role.py", "sys_user.py"}, write_route=False)
    do_trans(expect_classes={"order.py"}, write_route=False)
